﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using WordDocumentGenerator.Library;
using System.Diagnostics;
using System.Configuration;

namespace DbWord
{
    class Program
    {
        // 参数 第一参数 word 第二参数 xml
        // 本程序自动从xml中取值 绑定到word中。
        // oracle 是dw层
        static void Main(string[] args)
        {
            try
            {
                Trace.AutoFlush = true;
                Console.WriteLine("Started building of word ...");

                Directory.CreateDirectory(ConfigurationManager.AppSettings["TempDirectory"]);

                DateTime thisDate = DateTime.Now.AddDays(-7);
                if (args.Length > 0 && 
                    !DateTime.TryParse(args[0], out thisDate))
                {
                    Console.WriteLine("Input datetime invalid, please input again.");
                    return;
                }

                ParametersCache.Instance.InitByDateTime(thisDate);
                new Program().InitData();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Concat(ex.Message, "\r\n", ex.StackTrace));
            }
        }

        void InitData()
        {
            // Test document generation from template("Test_Template - 1.docx")
            DocumentGenerationInfo docinfo = GetDocInfo(
                "Openxml 2.0 builder ver 0.1 alpha",
                "1.0",
                null,
                Defs.WordFile,
                false);

            MyDocGenerator myDocGenerator = new MyDocGenerator(docinfo);
            myDocGenerator.RptTime = new DateTime(2014, 4, 14);

            byte[] result = myDocGenerator.GenerateDocument();

            // remove label
            //byte[] primaryDoc = File.ReadAllBytes(Defs.FinalPath);
            //List<byte[]> otherDocs = new List<byte[]>();
            //otherDocs.Add(result);
            //OpenXmlHelper openXmlHelper = new OpenXmlHelper(DocumentGenerationInfo.NamespaceUri);
            //byte[] result2 = openXmlHelper.AppendDocumentsToPrimaryDocument(primaryDoc, otherDocs);

            string file = Path.Combine(
                ConfigurationManager.AppSettings["TempDirectory"], 
                Guid.NewGuid().ToString() + ".docx");
            WriteOutputToFile(file, result);

            ChartHelper chartupdater = new ChartHelper();
            chartupdater.UpdateChart(file);

            File.Move(
                file, 
                Path.Combine(ConfigurationManager.AppSettings["DestDirectory"], ParametersCache.Instance.DestFilename)
                );

            Trace.WriteLine("Finsih. ");
        }

        /// <summary>
        /// Writes the output to file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="templateName">Name of the template.</param>
        /// <param name="fileContents">The file contents.</param>
        private static void WriteOutputToFile(
            string fileName, 
            byte[] fileContents)
        {
            ConsoleColor consoleColor = Console.ForegroundColor;

            if (fileContents != null)
            {
                File.WriteAllBytes(fileName, fileContents);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(string.Format("Generation succeeded for --> {0}", fileName));
                Console.WriteLine();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("Generation failed for {0}", fileName));
            }

            Console.ForegroundColor = consoleColor;
        }

        /// <summary>
        /// Gets the document generation info.
        /// </summary>
        /// <param name="docType">Type of the doc.</param>
        /// <param name="docVersion">The doc version.</param>
        /// <param name="dataContext">The data context.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="useDataBoundControls">if set to <c>true</c> [use data bound controls].</param>
        /// <returns></returns>
        private static DocumentGenerationInfo GetDocInfo(
            string docType, 
            string docVersion, 
            object dataContext, 
            string fileName, 
            bool useDataBoundControls)
        {
            DocumentGenerationInfo info = new DocumentGenerationInfo();
            info.Metadata = new DocumentMetadata() { DocumentType = docType, DocumentVersion = docVersion };
            info.DataContext = dataContext;
            info.TemplateData = File.ReadAllBytes(fileName);
            info.IsDataBoundControls = useDataBoundControls;

            return info;
        }
    }
}
